<?php
class Meta extends AppModel  {
	var $name = 'Meta';
 
	/*
	 * Get the meta model for the current page ($this->here from AppController).
	 */
	function __findCurrentPage($options = array()) {

		if (!isset($options['url'])) {
			return NULL;
		}
	
		$url = rtrim($options['url'], '/');
	
		/*
		 * First we try to find a complete match for the URL. If we can find it, or if
		 * we're at the root of the site, return the results.
		 */
		$meta = $this->find( array('url' => $url) );
		if (!empty($meta) || $url == '/') {
			return $meta;
		}else{
			$meta['Meta']['url'] = $url;
			$meta['Meta']['created'] = date('Y-m-d H:i:s');
			$meta['Meta']['modified'] = date('Y-m-d H:i:s');
			$this->create();
			$result = $this->save($meta);
		}
	
		/*
		 * We didn't find a match (or we're not in the root), so now we explode the URL
		 * into its parts (separated by /), and look for a match. In other words, we cascade
		 * down the URL until the root in order to find a meta entry.
		 */
		$urlParts = explode("/", trim($url, "/"));
		krsort($urlParts);
		$i = 0;
		foreach ((array)$urlParts as $part) {
			$url = str_replace('/'.$part, '', $url);
			
			if ($url && $i <= 3) {
				$meta = $this->find( array('url' => $url));
				if (!empty($meta)) {
					return $meta;
				}
			}
			$i++;
		}
	
		/*
		 * Still no matching meta, so now we just return the metas for the root.
		 */
		$meta = $this->find(array('url' => '/'));
		if(isset($meta['Meta']['keywords'])){
			$meta['Meta']['keywords'] .= Inflector::slug(str_replace('-',',',' '.implode(",",$urlParts)));
		}else{
			$meta['Meta']['keywords'] = Inflector::slug(str_replace('-',',',' '.implode(",",$urlParts)));
		}
		return $meta;
	}
}